#!/bin/sh
# shellcheck shell=dash disable=SC2169
#
# start/stop cron daemon
#

# function to update the crontab file and
# make sure that it is up to date
init() {
  # make sure the user crontabs directory exists
  # in /usr/local
  if [ ! -d /usr/local/crontabs ]; then
    mkdir -p /usr/local/crontabs
    chmod 775 /usr/local/crontabs
  fi

  # make sure that the /usr/local/crontabs/root file
  # exists where the user can put own stuff
  if [ ! -f /usr/local/crontabs/root ]; then
    touch /usr/local/crontabs/root
  fi

  # make sure /var/spool/cron/crontabs exists
  if [ ! -d /var/spool/cron/crontabs ]; then
    mkdir -p /var/spool/cron/crontabs
    chmod 775 /var/spool/cron/crontabs
  fi

  # make sure our system-wide crontab is taken for
  # being merged with the user configuration crontab
  cp -a /etc/crontab.root /var/spool/cron/crontabs/root

  # now we merge /usr/local/crontabs/root and /etc/crontab.root with the
  # latter having preference
  EXCLUDE_PATTERN="setHWClock.sh|SetInterfaceClock|logrotate"
  grep -viE "${EXCLUDE_PATTERN}" /usr/local/crontabs/root 2>/dev/null >>/var/spool/cron/crontabs/root

  # now we cleanup the user modified crontab
  if grep -qiE "${EXCLUDE_PATTERN}" /usr/local/crontabs/root; then
    grep -viE "${EXCLUDE_PATTERN}" /usr/local/crontabs/root 2>/dev/null >/tmp/cron.root
    mv -f /tmp/cron.root /usr/local/crontabs/root
  fi
}

start() {
  echo -n "Starting crond: "
  init
  start-stop-daemon -S -q -b -m -p /var/run/crond.pid --exec /usr/sbin/crond -- -f -l 9
  echo "OK"
}

stop () {
  echo -n "Stopping crond: "
  start-stop-daemon -K -q -p /var/run/crond.pid
  echo "OK"
}

restart() {
  stop
  sleep 1
  start
}

case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart|reload)
    restart
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
